<template>
    <div class="layout-route">
        <!-- <div class="header" style="margin-bottom: 16px"><el-button icon="el-icon-arrow-left" @click="cancel">返回</el-button><span style="margin-left: 16px">SPU列表</span></div> -->
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="110px">
                <el-form-item label="商品spu" prop="spu">
                    <el-input v-model.trim="queryParams.spu" placeholder="请输入商品spu" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="产品分类" prop="product_type">
                    <el-select v-model="queryParams.product_type" placeholder="请选择产品分类" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.productType" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="热销分类" prop="hot_type">
                    <el-select v-model="queryParams.hot_type" placeholder="请选择热销分类" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.hotType" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="供应商" prop="supply_id">
                    <SelectPage
                        v-model="queryParams.supply_id"
                        placeholder="请选择供应商"
                        :url="$api.supply.getSupplyList"
                        show_field="supply_name"
                        query_field="supply_name"
                        query_field2="spu"
                        filterable
                        clearable
                        popper-class="custom-select"
                        style="width: 240px"
                    ></SelectPage>
                </el-form-item>
                <el-form-item label="审核状态" prop="check_status">
                    <el-select v-model="queryParams.check_status" placeholder="请选择审核状态" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.checkStatus" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间" prop="create_time">
                    <el-date-picker v-model="queryParams.create_time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <!-- <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-edit" @click="batchOperate('place')">批量下单</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-edit-outline" @click="batchOperate('check')">批量审核</el-button>
                </el-col> -->
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table ref="sortTable" v-loading="loading" :data="tableData" row-key="id" border script @sort-change="handleSortChange" @selection-change="handleSelectionChange">
                <el-table-column label="" type="selection" width="55"></el-table-column>
                <el-table-column label="商品信息" prop="order_id" min-width="280">
                    <template slot-scope="scope">
                        <div class="flex">
                            <div style="width: 70px">
                                <ImageUploadImg v-model="scope.row.image_url" :readOnly="true" class="small-img"></ImageUploadImg>
                            </div>
                            <div>
                                <div>{{ scope.row.supply_name }}</div>
                                <el-link type="primary" @click="togoDetail(scope.row)">{{ scope.row.spu }}</el-link>
                                <div>{{ scope.row.hot_type | formatLabelByValueFuzzy(dict.hotType) }}</div>
                                <div>{{ scope.row.product_type | formatLabelByValueFuzzy(dict.productType) }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="基础数据" align="center">
                    <el-table-column label="库存" min-width="100" align="center" prop="inventory_quantity" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="库存总数" placement="top">
                                <el-link type="info">库存</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="在途" min-width="100" align="center" prop="on_way_quantity" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="sku已下单未入库的数量" placement="top">
                                <el-link type="info">在途</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单" min-width="100" align="center" prop="not_send_quantity" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="未发订单中需要sku的数量" placement="top">
                                <el-link type="info">订单</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="智能预测备货量" align="center">
                    <el-table-column label="货期" min-width="140" align="center" prop="produce_days" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="工厂做货周期" placement="top">
                                <el-link type="info">货期</el-link>
                            </el-tooltip>
                        </template>
                        <template slot-scope="scope">
                            <span slot="reference" @click="showEditPopover(scope.row, 'produce_days')" v-if="!scope.row.edit_produce_days">
                                {{ scope.row.produce_days }}
                                <i class="el-icon-edit-outline" ref="editBtn" style="color: #11a983"></i>
                            </span>
                            <div class="flex items-center justify-between" v-else>
                                <el-input
                                    v-model="editModal.produce_days"
                                    :autofocus="true"
                                    @blur="editBlur(scope.row, 'produce_days')"
                                    placeholder="请输入"
                                    size="mini"
                                    style="width: 80px"
                                    v-if="scope.row.edit_produce_days"
                                ></el-input>
                                <el-button size="mini" type="text" style="padding: 7px 4px" @click="updatePurchaseQuantity('produce_days')">确定</el-button>
                                <el-button size="mini" type="text" style="margin-left: 0" @click="hideEditPopover(scope.row, 'produce_days')">取消</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="安全" min-width="100" align="center" prop="safe_quantity">
                        <template #header>
                            <el-tooltip content="平均日销*备货天数" placement="top">
                                <el-link type="info">安全</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="备货" min-width="140" align="center" prop="suggest_days">
                        <template #header>
                            <el-tooltip content="根据产品热销类型设置的备货天数" placement="top">
                                <el-link type="info">备货</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="日均" min-width="100" align="center" prop="sku_1days" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="根据产品热销类型备货天数内的评均销量" placement="top">
                                <el-link type="info">日均</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="建议备货量" min-width="140" align="center" prop="suggest_sku_nums" sortable="custom" :sort-orders="['descending', 'ascending']">
                    <template #header>
                        <el-tooltip content="平均日销*(货期+物流+安全库存天数)+订单未发-(在途+总库存)" placement="top">
                            <el-link type="info">建议备货量</el-link>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="备货幅值" min-width="140" prop="suggest_rate">
                    <template slot-scope="scope">
                        <span slot="reference" @click="showEditPopover(scope.row, 'suggest_rate')" v-if="!scope.row.edit_suggest_rate">
                            {{ scope.row.suggest_rate }}
                            <i class="el-icon-edit-outline" ref="editBtn" style="color: #11a983"></i>
                        </span>
                        <div class="flex items-center justify-between" v-else>
                            <el-input
                                v-model="editModal.suggest_rate"
                                :autofocus="true"
                                @blur="editBlur(scope.row, 'suggest_rate')"
                                placeholder="请输入"
                                size="mini"
                                style="width: 80px"
                                v-if="scope.row.edit_suggest_rate"
                            ></el-input>
                            <el-button size="mini" type="text" style="padding: 7px 4px" @click="updatePurchaseQuantity('suggest_rate')">确定</el-button>
                            <el-button size="mini" type="text" style="margin-left: 0" @click="hideEditPopover(scope.row, 'suggest_rate')">取消</el-button>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" min-width="160" prop="create_time"></el-table-column>
                <!-- <el-table-column label="操作" width="120" fixed="right">
                        <template slot-scope="scope">
                            <div><el-button type="text" @click="operateRow(scope.row, 'place')">确认下单</el-button></div>
                            <div><el-button type="text" @click="operateRow(scope.row, 'check')">审核通过</el-button></div>
                        </template>
                    </el-table-column> -->
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" />
        </div>
        <!-- <SpuDetailDialog v-if="detailDialog.visible" v-model="detailDialog.visible" :params="detailDialog.data"></SpuDetailDialog> -->
        <DetailDialog v-if="detailDialog.visible" v-model="detailDialog.visible" :params="detailDialog.data"></DetailDialog>
    </div>
</template>

<script>
import { getSpuSuggest, exportSpuSuggest, editPlanSuggest, editSuggestSkuNums, editSuggestRate, planSuggestCheckStatus, planSuggestPlaceStatus } from '@/api/purchase'
import { exportFile } from '@/utils/index'
import { parseTime } from '@/utils/quickadmin'
import SpuDetailDialog from './spuDetailDialog'
import DetailDialog from './detailDialog.vue'
export default {
    name: 'PurchaseSupList',
    components: { SpuDetailDialog, DetailDialog },
    data() {
        return {
            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            total_inventory_quantity: 0,
            total_not_send_quantity: 0,
            total_on_way_quantity: 0,
            total_all_inventory_quantity: 0,

            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                supply_id: undefined,
                spu: undefined,
                hot_type: undefined,
                product_type: undefined,
                create_time: [],
                check_status: undefined,
                inventory_quantity: undefined,
                on_way_quantity: undefined,
                not_send_quantity: undefined,
                sku_1days: undefined,
                suggest_sku_nums: undefined,
                produce_days: undefined,
            },
            detailDialog: {
                visible: false,
                data: {},
            },
            // 状态数据字典
            dict: {
                productType: [
                    { label: 'bar类型', value: 1 },
                    { label: 'shapewear类型', value: 2 },
                    { label: 'swim类型', value: 3 },
                    { label: 'panties类型', value: 4 },
                    { label: '其他', value: 5 },
                ],
                hotType: [
                    { label: '热销', value: 1 },
                    { label: '潜力款', value: 2 },
                    { label: '新品', value: 3 },
                    { label: '中长尾款', value: 4 },
                ],
                placeStatus: [
                    { label: '待下单', value: 1 },
                    { label: '确认下单', value: 2 },
                ],
                checkStatus: [
                    { label: '待审核', value: 1 },
                    { label: '审核通过', value: 2 },
                ],
            },
            editModal: {
                id: '',
                suggest_sku_nums: '',
                produce_days: '',
                suggest_rate: '',
                spu: '',
            },
            multipleSelection: [],
        }
    },

    created() {
        this.getList()
    },
    methods: {
        operateRow(row, type, multiple = false) {
            if (type == 'check') {
                this.$confirm('确定要审核通过吗？').then(() => {
                    this.operateFunc(row, type, multiple)
                })
            } else {
                this.operateFunc(row, type, multiple)
            }
        },
        operateFunc(row, type, multiple) {
            let params = {}
            if (multiple) {
                params.spu = this.multipleSelection.map(item => item.spu).join(',')
            } else {
                params = { id: row.id, spu: row.spu }
            }
            const request = type == 'check' ? planSuggestCheckStatus(params) : planSuggestPlaceStatus(params)
            request.then(res => {
                this.msgSuccess('操作成功')
                this.multipleSelection = []
                this.getList()
            })
        },
        resetSort() {
            this.queryParams.inventory_quantity = undefined
            this.queryParams.on_way_quantity = undefined
            this.queryParams.not_send_quantity = undefined
            this.queryParams.sku_1days = undefined
            this.queryParams.suggest_sku_nums = undefined
            this.queryParams.produce_days = undefined
        },
        handleSortChange({ column, prop, order }) {
            this.resetSort()
            this.queryParams[prop] = order === 'descending' ? 'desc' : order === 'ascending' ? 'asc' : undefined
            this.getList()
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        batchOperate(type) {
            if (this.multipleSelection.length == 0) {
                this.msgError('请选择要操作的数据')
                return
            }
        },
        togoDetail(row) {
            // this.$emit('jump', { spu: row.spu })
            this.showDetailDialog(row)
        },
        cancel() {
            this.$emit('cancel')
        },
        showDetailDialog(row) {
            this.detailDialog.visible = true
            this.detailDialog.data = row
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            if (this.multipleSelection.length > 0) {
                qyparams.spu = this.multipleSelection.map(item => item.spu).join(',')
            }
            exportSpuSuggest(qyparams)
                .then(res => {
                    exportFile(res, () => {
                        this.download = false
                        this.multipleSelection = []
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        handleClick() {
            this.getList()
        },

        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            getSpuSuggest(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.tableData = this.tableData.map(item => {
                        item.edit_produce_days = false
                        item.edit_suggest_rate = false
                        return { ...item }
                    })
                    this.total = response.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')
            this.resetSort()
            this.$refs.sortTable.clearSort()
            this.handleQuery()
        },
        showEditPopover(row, type) {
            this.tableData = this.tableData.map(item => {
                if (item.id === row.id) {
                    return { ...item, [`edit_${type}`]: true }
                } else {
                    return { ...item, [`edit_${type}`]: false }
                }
            })

            this.editModal.id = row.id
            this.editModal.suggest_sku_nums = row.suggest_sku_nums
            this.editModal.produce_days = row.produce_days
            this.editModal.suggest_rate = row.suggest_rate
            this.editModal.spu = row.spu
        },
        editBlur(row, type) {
            setTimeout(() => {
                this.hideEditPopover(row, type)
            }, 500)
        },
        hideEditPopover(row, type) {
            this.tableData = this.tableData.map(item => {
                return { ...item, [`edit_${type}`]: false }
            })
            this.editModal.id = ''
            this.editModal.suggest_sku_nums = ''
            this.editModal.produce_days = ''
            this.editModal.suggest_rate = ''
            this.editModal.spu = ''
        },

        updatePurchaseQuantity(type) {
            const map = {
                suggest_sku_nums: editPlanSuggest,
                produce_days: editSuggestSkuNums,
                suggest_rate: editSuggestRate,
            }
            const request = map[type]
            const params = Object.assign({}, this.editModal)
            if (type === 'produce_days') {
                delete params.suggest_sku_nums
                delete params.suggest_rate
            }
            if (type === 'suggest_sku_nums') {
                delete params.produce_days
                delete params.suggest_rate
            }
            if (type === 'suggest_rate') {
                delete params.suggest_sku_nums
                delete params.produce_days
            }
            request(params).then(res => {
                this.msgSuccess('操作成功')
                this.getList()
            })
        },
    },
}
</script>

<style>
.total-warp {
    font-size: 18px;
    font-weight: bold;
    padding: 8px 0 16px 0;
}
</style>
